Good Programming Practices
Whenever we develop programs, the correctness of the program (whether it produces the "right" results) is a very important concern, but it is not the only concern. Other important factors include efficiency and programming style. Efficiency refers to whether the program runs in a reasonable amount of time and uses a reasonable amount of memory. These guidelines represent some common good practices in programming.
- include a program header (as comments) at the top of each file to indicate: what the program does, who wrote it, and when it was written and or revised
- choose clear and understandable algorithms over clever but hard to follow algorithms
- use descriptive names variables, functions and programs (follow naming conventions)
- use blank lines to separate logical units of code from each other (this is similar to the use of blank lines to separate paragraphs of a term paper)
- keep each line of the program to less then the screen width (usually 80 characters) so that it is not necessary to scroll right and left to read the code
- use brief and descriptive comments to document the algorithm and to record any information that you want to remember for future work on the program
Comments are an important and effective way of making our programs easier to
read and understand (as well as debug). Comments are meant for humans to read;
in fact, Matlab ignores all comments when it executes code. Comments in Matlab
begin with a percent sign ( %
) and continue to the end of the line.
Use comments in the code to document what your code does or provide an external document
that describes the purpose, inputs, and outputs, of your program.
Here's a program that illustrates these guidelines.
% Program that converts height in feet and inches to meters % Author(s): Becky Badger, Bucky Badger % Version: 1.0.01 % Date: October 1, 2006 % Input the data (may use input command here or read from file) feet = inputHeight(1) ; % may input from user or file inch = inputHeight(2) ; % Calculate height in inches and meters, uses 2.54 cm/in MPI = 0.0254 ; heightIn = feet*12 + inch ; heightM = heightIn * MPI ; % Output the height to the user in an easy to read form disp( ['The height ', num2str(feet), 'feet ', num2str(inch), ... 'inches = ', num2str(heightM), ' meters']);